import 'dart:async';
import 'package:flutter/material.dart';
import 'package:qgchat/bloc/blocProvider.dart';
import 'package:qgchat/common/global/global.dart';
import 'package:qgchat/http/apis/user.dart';
import 'package:qgchat/http/models/ReflectRecordModel.dart';
import 'package:qgchat/states/states_model/index.dart';

class CashOutBloc implements BlocBase {
  CashOutBloc() {
    userGlod();
  }

  // ##########  DEFAULT  ##############

  /// 用户总金额默认值
  ReflectRecordModel tomalsum = ReflectRecordModel.fromJson({'tomalsum': 0});

  /// 提现输入框控制器
  TextEditingController cashOutController;

  // ##########  STREAMS  ##############

  /// 用户总金额stream
  StreamController _userGlod = StreamController.broadcast();
  Sink get _userGlodSink => _userGlod.sink;
  Stream get userGlodStream => _userGlod.stream;

  /// 提现stream
  StreamController _cashout = StreamController.broadcast();
  Stream get cashoutStream => _cashout.stream;

  void dispose() {
    _userGlod.close();
    _cashout.close();
  }

  // ##########  HANDLING  ##############

  /// 用户总金额
  void userGlod() async {
    UserState user = state(Global.context, 'user');
    ReflectRecordModel result =
        await UserApis.reflectRecord(user.info.memberToken);
    if (result.tomalsum == null) {
      result.tomalsum = 0;
    }
    tomalsum = result;
    _userGlodSink.add(result);
  }

  /// 修改提现输入框金额
  void modifyGlod() {
    String text = tomalsum.tomalsum.toString();
    cashOutController.text = text;
    cashOutController.selection =
        TextSelection.collapsed(offset: text.runes.length);
  }

  /// 立即提现
  void cashout(memberToken, count, name, type) async {
    String money = cashOutController.text;
    if (double.parse(money) < 200) {
      showToast('必须大于200,请重新输入');
      return;
    }
    if (double.parse(money) % 100 != 0) {
      showToast('必须为100的倍数,请重新输入');
      return;
    }
    Map result = await UserApis.reflect(memberToken, count, name, money, type);
    if (result != null && result['status'] == 1) {
      userGlod();
      showToast('提现成功');
    }
  }
}
